﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using HaterAide.Interfaces;
using HaterAide.Mappings;
using HaterAide.SQL.DataClasses.Objects;
using Utilities.SQL;
#endregion

namespace HaterAide.SQL.SQLServer.Statements
{
    /// <summary>
    /// Contains functions dealing with lists
    /// </summary>
    internal static class List
    {
        #region Public Static Functions

        public static T LoadLists<T>(T ReturnValue, object IDValue, IClass ClassDefinition,
            IAttributeMap ClassMapping, IClassManager ClassManager, IMappingManager MappingManager,
            SQLHelper Helper)
        {
            if (ReturnValue == null)
                return default(T);
            for (int x = 0; x < ClassMapping.Properties.Count; ++x)
            {
                HaterAide.Mappings.Attribute Property = ClassMapping.Properties[x];
                if ((Utilities.Reflection.Reflection.IsIEnumerable(Property.Type)
                        &&!Utilities.Reflection.Reflection.IsOfType(Property.Type, typeof(string))) 
                    && Property.MappingType == AttributeType.Reference)
                {
                    string PropertyName = ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).ParentTable.Name + ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).Name;
                    SqlDbType IDType = ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).DataType;
                    Helper.Command = Property.MappedTable + "_Select_By_" + PropertyName;
                    if (IDType == SqlDbType.NVarChar)
                    {
                        Helper.AddParameter("@" + PropertyName, (string)IDValue, Property.Length);
                    }
                    else
                    {
                        Helper.AddParameter("@" + PropertyName, IDValue, IDType);
                    }
                    Helper.ExecuteReader();
                    object ListValue = Activator.CreateInstance(Property.Type);
                    Utilities.Reflection.Reflection.SetValue(ListValue, ReturnValue, Property.Name, "");
                    //object CurrentList = //Utilities.Reflection.Reflection.GetPropertyValue(ReturnValue, Property.Name);
                    while (Helper.Read())
                    {
                        Utilities.Reflection.Reflection.CallMethod("Add", ListValue, Helper.GetParameter(Property.Name, null));
                    }
                }
                else if (Property.MappingType == AttributeType.ManyToOne
                    && !Utilities.Reflection.Reflection.IsIEnumerable(Property.Type))
                {
                    FieldInfo TempField = ReturnValue.GetType().GetField("_" + Property.Name + "IDDerived");
                    string PropertyName = ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).ParentTable.Name + ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).Name;
                    Type MappedClassType = Property.Type;
                    IAttributeMap MappedClassMapping = null;
                    IClass MappedClassDefinition = null;
                    if (MappingManager.ClassMappings.ContainsKey(MappedClassType))
                    {
                        MappedClassMapping = MappingManager.ClassMappings[MappedClassType];
                        MappedClassDefinition = ClassManager[MappedClassType];
                    }
                    else
                    {
                        MappedClassMapping = MappingManager.ClassMappings[MappedClassType.BaseType];
                        MappedClassDefinition = ClassManager[MappedClassType.BaseType];
                    }
                    string MappedIDName = ((HaterAide.SQL.DataClasses.Column)MappedClassMapping.IDProperties[0].AssociatedTable).Name;
                    string MappedPropertyName = "";
                    if (MappedClassMapping.AssociatedTable.Name.EndsWith("_"))
                    {
                        MappedPropertyName = MappedClassMapping.AssociatedTable.Name + MappedIDName;
                    }
                    else
                    {
                        MappedPropertyName = MappedClassMapping.AssociatedTable.Name + "_" + MappedIDName;
                    }
                    //string MappedPropertyName = MappedClassType.Name + "_" + MappedIDName;
                    SqlDbType IDType = ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).DataType;
                    Helper.Command = Property.MappedTable + "_Select_By_" + PropertyName;
                    if (IDType == SqlDbType.NVarChar)
                    {
                        Helper.AddParameter("@" + PropertyName, (string)IDValue, Property.Length);
                    }
                    else
                    {
                        Helper.AddParameter("@" + PropertyName, IDValue, IDType);
                    }
                    Helper.ExecuteReader();
                    if (Helper.Read())
                    {
                        object FieldValue = Helper.GetParameter(MappedPropertyName, null);
                        TempField.SetValue(ReturnValue, FieldValue);
                    }
                }
            }
            return ReturnValue;
        }

        internal static System.Collections.Generic.IEnumerable<DataClasses.Objects.Command> GetDeleteListsCommands(object Object, Type ObjectType, IAttributeMap ClassMapping, IClass ClassDefinition)
        {
            List<Command> Commands = new List<Command>();
            if (Object == null)
                return Commands;
            List<string> ChangedItems = new List<string>();
            bool Update = false;
            if (Object is IHaterAideObject && ((IHaterAideObject)Object).Update0)
            {
                ChangedItems = ((IHaterAideObject)Object).ChangedList0;
                Update = true;
            }
            string IDName = ClassMapping.IDProperties[0].Name;
            SqlDbType IDType = ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).DataType;
            object IDObject = Utilities.Reflection.Reflection.GetPropertyValue(Object, IDName);
            foreach (HaterAide.Mappings.Attribute Property in ClassMapping.Properties)
            {
                if (Property.MappingType == AttributeType.ManyToOne
                    || Property.MappingType == AttributeType.ManyToMany
                    || (Property.MappingType == AttributeType.Reference
                        && (Utilities.Reflection.Reflection.IsIEnumerable(Property.Type)
                            &&!Utilities.Reflection.Reflection.IsOfType(Property.Type, typeof(string)))))
                {
                    if (ChangedItems.Contains(Property.Name) || !Update)
                    {
                        Command Temp = new Command();
                        string PropertyName = ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).ParentTable.Name + ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).Name;
                        Temp.CommandType = Enums.CommandType.NonQuery;
                        Temp.StoredProcedure = Property.MappedTable + "_Delete_By_" + PropertyName;
                        if (IDType == SqlDbType.NVarChar)
                        {
                            Temp.Variables.Add(new Variable("@" + PropertyName, (string)IDObject, Property.Length));
                        }
                        else
                        {
                            Temp.Variables.Add(new Variable("@" + PropertyName, IDObject, IDType));
                        }
                        object Value = Utilities.Reflection.Reflection.GetPropertyValue(Object, Property.Name);
                        Commands.Add(Temp);
                    }
                }
            }
            return Commands;
        }

        internal static System.Collections.Generic.IEnumerable<DataClasses.Objects.Command> GetSetupListsCommands(object Object, Type ObjectType, IAttributeMap ClassMapping, IClass ClassDefinition, IMappingManager MappingManager, IClassManager ClassManager)
        {
            List<Command> Commands = new List<Command>();
            if (Object == null)
                return Commands;
            List<string> ChangedItems = new List<string>();
            bool Update = false;
            if (Object is IHaterAideObject && ((IHaterAideObject)Object).Update0)
            {
                ChangedItems = ((IHaterAideObject)Object).ChangedList0;
                Update = true;
            }
            string IDName = ClassMapping.IDProperties[0].Name;
            object IDObject = Utilities.Reflection.Reflection.GetPropertyValue(Object, IDName);
            SqlDbType IDDataType = ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).DataType;
            foreach (HaterAide.Mappings.Attribute Property in ClassMapping.Properties)
            {
                if (ChangedItems.Contains(Property.Name) || !Update)
                {
                    if (Property.MappingType == AttributeType.ManyToOne || Property.MappingType == AttributeType.ManyToMany)
                    {
                        object Value = Utilities.Reflection.Reflection.GetPropertyValue(Object, Property.Name);
                        if (Value != null)
                        {
                            if (Value is IEnumerable)
                            {
                                IEnumerable TempValue = (IEnumerable)Value;
                                foreach (object MappedClassObject in TempValue)
                                {
                                    Commands.Add(GetInsertListItemCommands(ClassMapping, ClassDefinition, ClassManager, MappingManager, IDObject, IDDataType, Property, MappedClassObject));
                                }
                            }
                            else
                            {
                                Commands.Add(GetInsertListItemCommands(ClassMapping, ClassDefinition, ClassManager, MappingManager, IDObject, IDDataType, Property, Value));
                            }
                        }
                    }
                    else if (Property.MappingType == AttributeType.Reference
                            && (Utilities.Reflection.Reflection.IsIEnumerable(Property.Type)
                                &&!Utilities.Reflection.Reflection.IsOfType(Property.Type, typeof(string))))
                    {
                        object Value = Utilities.Reflection.Reflection.GetPropertyValue(Object, Property.Name);
                        if (Value != null)
                        {
                            IEnumerable TempValue = (IEnumerable)Value;
                            foreach (object MappedObject in TempValue)
                            {
                                Command TempCommand = new Command();
                                TempCommand.CommandType = Enums.CommandType.NonQuery;
                                TempCommand.StoredProcedure = Property.MappedTable + "_Insert";

                                if (IDDataType == SqlDbType.NVarChar)
                                {
                                    TempCommand.Variables.Add(new Variable("@" + ((HaterAide.SQL.DataClasses.Table)ClassMapping.AssociatedTable).Name + ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).Name, (string)IDObject, ClassMapping.IDProperties[0].Length));
                                }
                                else
                                {
                                    TempCommand.Variables.Add(new Variable("@" + ((HaterAide.SQL.DataClasses.Table)ClassMapping.AssociatedTable).Name + ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).Name, IDObject, IDDataType));
                                }
                                SqlDbType MappedIDDataType = SQL.Helpers.GlobalFunctions.GetSQLType(MappedObject.GetType());
                                if (MappedIDDataType == SqlDbType.NVarChar)
                                {
                                    TempCommand.Variables.Add(new Variable("@" + Property.Name, (string)MappedObject, Property.Length));
                                }
                                else
                                {
                                    TempCommand.Variables.Add(new Variable("@" + Property.Name, MappedObject, MappedIDDataType));
                                }
                                Commands.Add(TempCommand);
                            }
                        }
                    }
                }
            }
            return Commands;
        }

        private static Command GetInsertListItemCommands(IAttributeMap ClassMapping, IClass ClassDefinition, IClassManager ClassManager, IMappingManager MappingManager, object IDObject, SqlDbType IDDataType, Mappings.Attribute Property, object MappedClassObject)
        {
            Type MappedClassType = MappedClassObject.GetType();
            IAttributeMap MappedClassMapping = null;
            IClass MappedClassDefinition = null;
            if (MappingManager.ClassMappings.ContainsKey(MappedClassType))
            {
                MappedClassMapping = MappingManager.ClassMappings[MappedClassType];
                MappedClassDefinition = ClassManager[MappedClassType];
            }
            else
            {
                MappedClassMapping = MappingManager.ClassMappings[MappedClassType.BaseType];
                MappedClassDefinition = ClassManager[MappedClassType.BaseType];
            }
            string MappedIDName = MappedClassMapping.IDProperties[0].Name;
            object MappedIDObject = Utilities.Reflection.Reflection.GetPropertyValue(MappedClassObject, MappedIDName);
            SqlDbType MappedIDDataType = ((HaterAide.SQL.DataClasses.Column)MappedClassMapping.IDProperties[0].AssociatedTable).DataType;
            Command TempCommand = new Command();
            TempCommand.StoredProcedure = Property.MappedTable + "_Insert";
            TempCommand.CommandType = Enums.CommandType.NonQuery;
            if (MappedIDDataType == SqlDbType.NVarChar)
            {
                TempCommand.Variables.Add(new Variable("@" + ((HaterAide.SQL.DataClasses.Table)MappedClassMapping.AssociatedTable).Name + ((HaterAide.SQL.DataClasses.Column)MappedClassMapping.IDProperties[0].AssociatedTable).Name, (string)MappedIDObject, MappedClassMapping.IDProperties[0].Length));
            }
            else
            {
                TempCommand.Variables.Add(new Variable("@" + ((HaterAide.SQL.DataClasses.Table)MappedClassMapping.AssociatedTable).Name + ((HaterAide.SQL.DataClasses.Column)MappedClassMapping.IDProperties[0].AssociatedTable).Name, MappedIDObject, MappedIDDataType));
            }
            if (IDDataType == SqlDbType.NVarChar)
            {
                TempCommand.Variables.Add(new Variable("@" + ((HaterAide.SQL.DataClasses.Table)ClassMapping.AssociatedTable).Name + ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).Name, (string)IDObject, ClassMapping.IDProperties[0].Length));
            }
            else
            {
                TempCommand.Variables.Add(new Variable("@" + ((HaterAide.SQL.DataClasses.Table)ClassMapping.AssociatedTable).Name + ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable).Name, IDObject, IDDataType));
            }
            return TempCommand;
        }

        #endregion
    }
}